<?php


namespace app\api\controller;


use app\service\model\CouponModel;
use app\service\model\MemberCouponModel;
use app\service\Y;
use think\Exception;
use think\facade\Db;

class Coupon extends AuthApi
{

    /**
     * 优惠券列表
     * @return \think\response\Json
     * @throws \app\service\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function coupon_list(): \think\response\Json
    {
        $data = CouponModel::where('is_permanent_validity', '=', 1)
            ->whereOr(function ($query) {
                $query->where('start_time', '<', date('Y-m-d H:i:s'))->where('end_time', '>', date('Y-m-d H:i:s'));
            })
            ->select();

        // 如果是已登录用户则标记已领取的优惠券
        foreach ($data as &$v) {
            if ($v->memberCoupon()->where('member_id', '=', $this->member->id)->find()) {
                $v['is_get'] = 1;
            } else {
                $v['is_get'] = 0;
            }
        }
        return Y::success($data, '优惠券列表');
    }

    /**
     * 用户可用优惠券列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function member_coupon_list(): \think\response\Json
    {
        $goods_total = input('param.goods_total', 0);
        $member_id = $this->member->id;

        $member_coupon = MemberCouponModel::hasWhere('coupon', function ($query) use ($goods_total) {
            $query->where(function ($query) {
                // 在有效期内或者永久有效
                $query->where(function ($query) {
                    $time = date('Y-m-d H:i:s');
                    $query->where('start_time', '<', $time)->where('end_time', '>', $time);
                })->whereOr('is_permanent_validity', '=', 1);
            })->where(function ($query) use ($goods_total) {
                // 不限金额或者商品金额大于限制金额
                $query->where(function ($query) use ($goods_total) {
                    $query->where('restrict', '>', $goods_total);
                })->whereOr('restrict', '=', 0);
            });
        })->with('coupon')->where('member_id', '=', $member_id)
            ->where('status', '=', 1)
            ->select();
        return Y::success($member_coupon, '用户可用优惠券列表');
    }

    /**
     * 领取优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_coupon()
    {
        $coupon_id = input('param.coupon_id', 0);
        $time = date('Y-m-d H:i:s');
        $coupon = CouponModel::where('id', '=', $coupon_id)
            ->where('start_time', '<', $time)
            ->where('end_time', '>', $time)
            ->find();
        if (!$coupon) {
            return Y::error('优惠券不可领取');
        }
        $member_coupon = MemberCouponModel::where('member_id', '=', $this->member->id)
            ->where('coupon_id', '=', $coupon_id)
            ->find();
        if ($member_coupon) {
            return Y::error('优惠券已领取');
        }
        Db::startTrans();
        try {
            MemberCouponModel::create([
                'member_id' => $this->member->id,
                'coupon_id' => $coupon_id
            ]);
            $coupon->inc('get_num')->update();
            Db::commit();
            return Y::success([], '领取成功');
        } catch (Exception $e) {
            Db::rollback();
            return Y::error('领取失败', [$e->getMessage(), $e->getFile(), $e->getCode()]);
        }
    }

}